package com.fei.vm;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VMFormat {

	public static void main(String[] args) {
		String document = "$name  $hobby: #foreach($hobby in $hobbyArray)    ${hobby} #end  ";
		new VMFormat().format(document);
	}

	/**
	 * @param document
	 */
	public String format(final String document) {
		String textBeforeFormatting = document;
		boolean isUppercaseEnabled = true;
		Pattern pattern = null;
		Matcher matcher = null;
		String newText = textBeforeFormatting;
		String patternStr = "^[\\s]*";
		String replacementStr = "";
		// put all the tags on newLine but not those which start
		// with ##
		pattern = Pattern.compile("<[/]?(?!textarea)[a-zA-Z]+");
		matcher = pattern.matcher(newText);
		StringBuffer buf = new StringBuffer();
		while ((matcher.find())) {
			// Get the match result
			String replaceStr = matcher.group();
			// Insert replacement
			matcher.appendReplacement(buf, replaceStr);
		}
		matcher.appendTail(buf);
		// Get result
		newText = buf.toString();
		String patternStrClose, replaceStrClose = "";
		patternStrClose = "(</.*?>|<.*?/>)";
		replaceStrClose = "$1\n";
		pattern = Pattern.compile(patternStrClose, Pattern.MULTILINE);
		matcher = pattern.matcher(newText);
		newText = matcher.replaceAll(replaceStrClose);
		patternStrClose = "(<(?!/)[a-zA-Z].*?>)\\s*?(?=<(?!/)[a-zA-Z].*?>)";
		replaceStrClose = "$1\n";
		pattern = Pattern.compile(patternStrClose, Pattern.MULTILINE);
		matcher = pattern.matcher(newText);
		newText = matcher.replaceAll(replaceStrClose);
		pattern = Pattern.compile(patternStr, Pattern.MULTILINE);
		matcher = pattern.matcher(newText);
		newText = matcher.replaceAll(replacementStr);

		System.out.println(newText);
		return document;
	}
}
